<template>
	<view class="wrap">
		<js-error mode="bottom" ref="jsError" @update:errorcClose="onErrorClose"></js-error>
		<view class="cu-bar search" style="padding: 10px" ref="cu-bar">
			<u-search v-model="barCode" ref="uSearch" :focus="focus" placeholder="请先聚焦后扫描机台" :show-action="false"
				@search="confirmSearch" height="74"></u-search>
			<view style="margin-left: 10px; display: flex; flex-direction: column">
				<u-icon @click="search" name="scan" size="60"></u-icon>
			</view>
		</view>
		<view class="cu-bar search" style="padding: 10px" ref="cuBar" v-if="lineCode">
			<u-form style="width: 100%;">
				<u-form-item label="机台" prop="id" label-width="180" style="font-weight: 800;">
					<view>{{ lineCode }}</view>
				</u-form-item>
			</u-form>
		</view>
		<view v-show="currentRW ">
			<scroll-view
			  scroll-y="true"
			  :style="{ height: computedScrollViewHeight }"
			  
			>
			<!-- style="margin: 20px 0" -->
				<view class="margin-sm">
					<u-section
					  title="当前机台正在加工任务"
					  
					  :right="false"
					  line-color="blue"
					  font-size="30"
					  v-if="list.length>0"
					></u-section>
					<view class="wrap" v-if="list.length>0">
						<u-form class="form" ref="uForm" label-position="left" :model="model">
							<div v-for="(item,index) in list">
								<u-form-item label="" prop="id" label-width="180" style="font-weight: 800;">
									<template>
										<view class="flex title">
											<view style=" display: inline-block;background: #3E97B0;color: #fff;width: 30px;text-align: center;font-style: italic;font-weight: bold;margin-right: 5px	;">
																{{ index + 1 }}
											</view>
											<!-- <view>订单号</view> -->
										</view>
										<view>{{ item.scOrder ? item.scOrder.code || '' : ''}}{{ item.scOrder ? item.scOrder.sortNum ? '#' + item.scOrder.sortNum : '' : ''}}</view>
									</template>
								</u-form-item>
								<u-form-item label="操作工" prop="operator" label-width="180" style="color: red;font-weight: 800;">
									<view class="flex">
										<u-input placeholder="请扫码" v-model="model.operator" type="text" maxlength="64" :custom-style="customStyle" disabled></u-input>
										<text class="cuIcon-roundclose" @tap="clearOperator" v-if="item.operator&&!flag"></text>
									</view>
								</u-form-item>
								<!-- <u-form-item label="订单号" prop="id" label-width="180" >
									<view>{{ item.scOrder.code || ''}}{{item.scOrder.sortNum ? '#' + item.scOrder.sortNum : ''}}</view>
								</u-form-item> -->
								
								<u-form-item label="上机操作工" prop="id" label-width="180">
									<view>{{ item.operator }}</view>
								</u-form-item>
								<u-form-item label="工序名称" prop="id" label-width="180">
									<view>{{ item.basOper.name}}</view>
								</u-form-item>
								<u-form-item label="存货编码" prop="id" label-width="180">
									<view>{{ item.basInv.cinvcode || ''}}</view>
								</u-form-item>
								<u-form-item label="存货名称" prop="id" label-width="180">
									<view>{{ item.basInv.cinvname || ''}}</view>
								</u-form-item>
								<u-form-item label="规格型号" prop="id" label-width="180">
									<view>{{ item.basInv.cinvstd || ''}}</view>
								</u-form-item>
							</div>
							
						</u-form>
					</view>
					<view v-if="list.length==0">
						<u-empty :style="{height: emptyViewHeight+'px'}">
							<template #bottom>
								<view>当前机台暂无执行任务</view>
							</template>
						</u-empty>
					</view>
					
				</view>
				
				
			</scroll-view>
			<view class="btn-group cu-bar foot padding" ref="btn-group" v-if="list.length>0">
				<!-- round -->
				<button class="cu-btn  bg-confirm lg margin-left " @click="confirm" v-if="!flag">下机</button>	
			</view>
		</view>
		
		<u-empty v-if="!currentRW" :style="{height: emptyViewHeight+'px'}"></u-empty>
		
			
		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				focus:true,
				barCode:'',
				model: {
					iqty:10,
					operator:''
				},
				rules: {
					operator: [
						{
							required: true,
							message: '请扫码操作工',
							trigger: ['change','blur'],
						}
					]
				},
				customStyle:{
					color:'red'
				},
				scrollViewHeight: 0,
				currentRW:false,
				emptyViewHeight:0,
				list:[],
				modid:'',
				operatorNames:{},
				lineCode:'',
				flag:false
			}
		},
		onShow() {
			// 在onShow中监听事件
			uni.$on('selectedItems', (selectedItems) => {
				this.list = [...this.list,...selectedItems]
			});
		},
		onLoad() {
			this.$nextTick(() => {
				this.calculateScrollViewHeight()
				this.emptyHeight()
			})
		},
		computed: {
		  computedScrollViewHeight() {
		    return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
		  },
		},
		onUnload(){
			uni.$off('selectedItems');
		},
		methods:{
			clearOperator(){
				this.showCustomModal("确定要删除操作工").then((res) => {
					if(res){
						this.model.operator = ''
						this.operatorNames = { }
						this.$forceUpdate()
					}
				})
			},
			async calculateScrollViewHeight() {
			  try {
			// 等待头部高度计算完成
			      console.log(this.$refs,'this.$refs')
			      // 计算btn-group 高度
			      // 获取屏幕高度
			      const systemInfo = uni.getSystemInfoSync();
			      const screenHeight = systemInfo.windowHeight;
				  const btnOffsetHeight = this.$refs['btn-group'] ? this.$refs['btn-group'].$el ? this.$refs['btn-group'].$el.offsetHeight : 0 : 0;
				  const cuBarOffsetHeight = this.$refs['cu-bar'] ? this.$refs['cu-bar'].$el ? this.$refs['cu-bar'].$el.offsetHeight : 109 : 0 ;
				  console.log(screenHeight,btnOffsetHeight,cuBarOffsetHeight,'===')
			      // 计算scroll-view高度
			      this.scrollViewHeight = screenHeight - ( btnOffsetHeight + cuBarOffsetHeight + 80 );
			  } catch (error) {
			    console.error('Error while calculating ScrollView height:', error);
			  }
			},
			async emptyHeight() {
			  try {
			      // 获取屏幕高度
			      const systemInfo = uni.getSystemInfoSync();
			      const screenHeight = systemInfo.windowHeight;
				  const cuBarOffsetHeight = this.$refs['cu-bar'] ? this.$refs['cu-bar'].$el ? this.$refs['cu-bar'].$el.offsetHeight :109 : 0;
			      // 计算scroll-view高度
			      this.emptyViewHeight = screenHeight - cuBarOffsetHeight;
			  } catch (error) {
			    console.error('Error while calculating ScrollView height:', error);
			  }
			},
			confirmSearch(){		
				this.focus = false
				this.commonSearch(this.barCode)
			},
			async commonSearch(barCode){				
				let JT = this.vuex_config.JT;
				let GP = this.vuex_config.GP;
				console.log(this.barCode.indexOf(JT),'JT',this.barCode,JT,this.barCode.indexOf(GP))
				if (barCode.indexOf(JT) == -1 && barCode.indexOf(GP) == -1) {
					this.$refs.jsError.showError('',"请扫描正确的机台或工牌",'error');
					return;
				}else if(barCode.indexOf(JT) == 0){

					const res = await this.$u.api.kst.checkFunAndBar({
						funcType:this.vuex_config.JT,
						barJT:barCode
					})
					if (res.result == "true") {
						await this.$nextTick();
						this.barCode = '';
						this.lineCode = res.basLine.code;
						const resResult = await this.$u.api.kst.getTaskByLineCode({
							lineCode:this.lineCode
						})
						if (resResult.result == "true") {
							this.currentRW = true;
							this.list = resResult.data
							this.modid = this.list.length > 0 ? this.list[0]['modid'] : ''
							setTimeout(() => {
								this.focus = true;
							}, 500);
						}else{
							setTimeout(() => {
								this.focus = true;
							}, 500);
							this.$refs.jsError.showError('',resResult.message,'error');
						}	

					}else{
						setTimeout(() => {
							this.focus = true;
						}, 500);
						this.$refs.jsError.showError('',res.message,'error');
						
					}
				}  else if(barCode.indexOf(GP) == 0){
					const res = await this.$u.api.kst.checkFunAndBar({
						funcType:this.vuex_config.GP,
						barGP:barCode
					})
					if(res.result == "true"){
						const operatorNameStr =  Array.from(new Set(this.list.map(item => item.operator))).join(',');
						console.log('operatorNameStr',operatorNameStr,operatorNameStr.includes(res.operator.name))
						if(operatorNameStr.includes(res.operator.name)){
							let operatorName = res.operator.name;
							
							let operatorCode = res.operator.code;
							
							let bmonitor = res.operator.bmonitor;
							
							// 累加操作员名称或设置初始值
							if (this.operatorNames[barCode]) {
								operatorName = `${this.operatorNames[barCode]},${operatorName}`;
							}
							this.operatorNames[barCode] = operatorName;
							// this.operatorNames 去重
							this.operatorNames = [...new Set(Object.values(this.operatorNames))]
							
							const operatorNamesStr = Object.values(this.operatorNames).join(',');
							await this.$nextTick();
							this.barCode = '';
							this.model.operator = operatorNamesStr
						}else{
							this.$refs.jsError.showError('', '请扫码当前机台的操作工', 'error');
						}
						setTimeout(() => {
							this.barCode = '';
							this.focusGP = true;
						}, 500);
						this.$forceUpdate()	
					}else{
						this.$refs.jsError.showError('', res.message, 'error');
						setTimeout(() => {
							this.barCode = '';
							this.focus = true;
						}, 500);
					}
				} 
				
			},

			confirm(){
				// 获取list的id,字符串逗号分隔
				this.$u.api.kst.taskDown({
					lineCode:this.lineCode,
					operator: this.model.operator ? this.model.operator : this.list[0].operator
				}).then((res)=>{
					if(res.result=="true"){
						this.flag = true
						this.$u.toast(res.message);
					}else{
						// this.$u.toast(res.message);
						this.$refs.jsError.showError('',res.message,'error');
					}
				})	
			},
			search(){
				var _that = this;
				_that.focus = false
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					// onlyFromCamera: true,
					success: async (res) => {
						_that.barCode = res.result;
						await _that.commonSearch(res.result)
					},
				});
			},
			selectSJ(){
				uni.navigateTo({
					url: "/pages/mes/shangji/bSelect?modid=" + this.modid + '&lineCode=' + this.lineCode
				});
			},
			onErrorClose(result) {
			//   this.$emit("update:errorcClose", result);
			//   获取focus 焦点
				this.focus = result;
				setTimeout(() => {
					this.barCode = ''
					this.focus = true;
				}, 100);
			},
		}
	}	
</script>

<style scoped>
	.title{
		width: 260rpx;
	}
	.bg-confirm {
	  background: #3e97b0;
	  color: #ffffff;
	}
</style>